package com.xdclass.mysql.dao;

import com.xdclass.mysql.model.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author daniel
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public Boolean add(User user) {
        String sql = "INSERT INTO user(id,NAME) VALUES(?,?)";
        return jdbcTemplate.update(sql, user.getId(), user.getName()) > 0;
    }

    @Override
    public Boolean update(User user) {
        String sql = "UPDATE user SET NAME = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getId()) > 0;
    }

    @Override
    public boolean delete(Long id) {
        String sql = "DELETE FROM user WHERE id = ?";
        return jdbcTemplate.update(sql, id) > 0;

    }

    @Override
    public User locate(Long id) {
        String sql = "SELECT * FROM user WHERE id=?";
        SqlRowSet rs = jdbcTemplate.queryForRowSet(sql, id);

        if (rs.next()) {
            return generateEntity(rs);
        }
        return null;
    }

    @Override
    public List<User> matchName(String name) {
        String sql = "SELECT * FROM user WHERE NAME LIKE ?";
        SqlRowSet rs = jdbcTemplate.queryForRowSet(sql, "%" + name + "%");
        List<User> users = new ArrayList<>();
        while (rs.next()) {
            users.add(generateEntity(rs));
        }
        return users;
    }

    private User generateEntity(SqlRowSet rs) {
        User weChatPay = new User();
        weChatPay.setId(rs.getLong("id"));
        weChatPay.setName(rs.getString("NAME"));
        return weChatPay;
    }
    
}
